<template>
  <div class="intercept-rules">
    <header class="mb-8">
      <h1 class="glow-text">拦截规则</h1>
      <div class="tech-line mt-2"></div>
    </header>

    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <div class="relative">
          <input
            type="text"
            class="input pr-10"
            placeholder="搜索规则..."
            v-model="searchQuery"
          />
          <svg class="w-5 h-5 absolute right-3 top-2.5 text-light-dark" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
          </svg>
        </div>

        <div class="ml-4">
          <select class="input bg-dark-darker" v-model="statusFilter">
            <option value="all">所有状态</option>
            <option value="active">活跃</option>
            <option value="inactive">非活跃</option>
          </select>
        </div>
      </div>

      <div class="flex space-x-2">
        <button @click="fetchRules" class="btn btn-outline">
          <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
          </svg>
          刷新
        </button>
        <button @click="clearRules" class="btn btn-danger">
          <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
          </svg>
          清除所有规则
        </button>
      </div>
    </div>

    <div v-if="loading" class="flex justify-center items-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="filteredRules.length === 0" class="text-center py-12 text-light-dark">
      暂无拦截规则
    </div>

    <div v-else class="overflow-x-auto">
      <table class="w-full">
        <thead>
          <tr class="border-b border-dark-light">
            <th class="py-3 px-4 text-left">服务名称</th>
            <th class="py-3 px-4 text-left">服务 IP</th>
            <th class="py-3 px-4 text-left">服务端口</th>
            <th class="py-3 px-4 text-left">代理端口</th>
            <th class="py-3 px-4 text-left">状态</th>
            <th class="py-3 px-4 text-left">创建时间</th>
            <th class="py-3 px-4 text-left">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="rule in filteredRules"
            :key="rule.id"
            class="border-b border-dark-light hover:bg-dark-darker"
          >
            <td class="py-3 px-4">{{ rule.service_name }}</td>
            <td class="py-3 px-4 font-mono">{{ rule.service_ip }}</td>
            <td class="py-3 px-4">{{ rule.service_port }}</td>
            <td class="py-3 px-4">{{ rule.proxy_port }}</td>
            <td class="py-3 px-4">
              <span :class="{
                'badge badge-blue': rule.is_active,
                'badge badge-yellow': !rule.is_active
              }">{{ rule.is_active ? '活跃' : '非活跃' }}</span>
            </td>
            <td class="py-3 px-4 text-light-dark">{{ formatTime(rule.created_at) }}</td>
            <td class="py-3 px-4">
              <button
                @click="toggleRuleStatus(rule)"
                :class="rule.is_active ? 'text-accent-yellow hover:text-accent-yellow/80' : 'text-accent-blue hover:text-accent-blue/80'"
                class="mr-2"
                :title="rule.is_active ? '停用' : '启用'"
              >
                <svg v-if="rule.is_active" class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <svg v-else class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
              </button>
              <button
                @click="deleteRule(rule.id)"
                class="text-accent-pink hover:text-accent-pink/80"
                title="删除"
              >
                <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                </svg>
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 分页 -->
      <div class="flex justify-between items-center mt-6">
        <div class="text-light-dark">
          共 {{ pagination.total }} 条记录，第 {{ pagination.page }} / {{ pagination.pages }} 页
        </div>
        <div class="flex space-x-2">
          <button
            @click="changePage(pagination.page - 1)"
            class="btn btn-outline py-1 px-3"
            :disabled="pagination.page <= 1"
          >
            上一页
          </button>
          <button
            @click="changePage(pagination.page + 1)"
            class="btn btn-outline py-1 px-3"
            :disabled="pagination.page >= pagination.pages"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 拦截状态卡片 -->
    <div class="card mt-8">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-medium">拦截状态</h2>
        <div class="flex space-x-2">
          <button 
            v-if="!interceptStatus.is_running" 
            @click="showStartInterceptModal = true" 
            class="btn btn-primary"
          >
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            开始拦截
          </button>
          <button 
            v-else 
            @click="stopIntercept" 
            class="btn btn-danger"
          >
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z"></path>
            </svg>
            停止拦截
          </button>
        </div>
      </div>

      <div v-if="loadingStatus" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
      </div>

      <div v-else class="bg-dark-darker p-6 rounded-lg">
        <div class="flex items-center mb-4">
          <div class="w-3 h-3 rounded-full mr-2" :class="interceptStatus.is_running ? 'bg-accent-blue animate-pulse' : 'bg-accent-pink'"></div>
          <h3 class="text-lg font-medium">拦截状态</h3>
        </div>
        <div class="text-2xl font-bold mb-2">{{ interceptStatus.is_running ? '正在拦截' : '未拦截' }}</div>
        <div class="text-light-dark">
          <div v-if="interceptStatus.is_running">
            <div>拦截规则数: {{ interceptStatus.rules?.length || 0 }}</div>
            <div>开始时间: {{ formatTime(interceptStatus.start_time) }}</div>
          </div>
          <div v-else>
            上次拦截时间: {{ interceptStatus.last_intercept_time ? formatTime(interceptStatus.last_intercept_time) : '无记录' }}
          </div>
        </div>
      </div>
    </div>

    <!-- 开始拦截弹窗 -->
    <div v-if="showStartInterceptModal" class="fixed inset-0 bg-dark-darker bg-opacity-75 flex items-center justify-center z-50">
      <div class="bg-dark-light rounded-lg w-full max-w-lg cyber-border">
        <div class="p-6">
          <div class="flex justify-between items-start mb-6">
            <h2 class="text-2xl font-bold">开始拦截</h2>
            <button @click="showStartInterceptModal = false" class="text-light-dark hover:text-primary">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div class="mb-6">
            <label class="block text-light-dark mb-2">选择服务</label>
            <div v-if="loadingServices" class="flex justify-center items-center py-4">
              <div class="animate-spin rounded-full h-6 w-6 border-t-2 border-b-2 border-primary"></div>
            </div>
            <div v-else-if="services.length === 0" class="text-center py-4 text-light-dark">
              暂无服务，请先添加服务
            </div>
            <div v-else class="max-h-60 overflow-y-auto bg-dark-darker rounded-lg p-2">
              <div
                v-for="service in services"
                :key="service._id"
                class="flex items-center p-2 hover:bg-dark-light rounded-md"
              >
                <input
                  type="checkbox"
                  :id="`service-${service._id}`"
                  v-model="interceptForm.service_ids"
                  :value="service._id"
                  class="mr-2"
                />
                <label :for="`service-${service._id}`" class="flex-1 cursor-pointer">
                  <div>{{ service.service_name }}</div>
                  <div class="text-sm text-light-dark">{{ service.service_ip }}:{{ service.service_port }}</div>
                </label>
              </div>
            </div>
          </div>

          <div class="flex justify-end">
            <button @click="showStartInterceptModal = false" class="btn btn-outline mr-2">取消</button>
            <button @click="startIntercept" class="btn btn-primary" :disabled="startingIntercept">
              <span v-if="startingIntercept">开始中...</span>
              <span v-else>开始拦截</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { interceptApi, servicesApi } from '../../api';

// 状态变量
const loading = ref(false);
const loadingStatus = ref(false);
const loadingServices = ref(false);
const startingIntercept = ref(false);
const showStartInterceptModal = ref(false);
const searchQuery = ref('');
const statusFilter = ref('all');

// 拦截规则列表
const rules = ref<any[]>([]);

// 拦截状态
const interceptStatus = ref({
  is_running: false,
  rules: [] as any[],
  start_time: '',
  last_intercept_time: ''
});

// 服务列表
const services = ref<any[]>([]);

// 拦截表单
const interceptForm = ref({
  service_ids: [] as string[]
});

// 分页
const pagination = ref({
  page: 1,
  page_size: 10,
  total: 0,
  pages: 1
});

// 过滤规则
const filteredRules = computed(() => {
  let result = rules.value;

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(rule =>
      rule.service_name?.toLowerCase().includes(query) ||
      rule.service_ip?.includes(query) ||
      rule.service_port?.toString().includes(query) ||
      rule.proxy_port?.toString().includes(query)
    );
  }

  // 状态过滤
  if (statusFilter.value !== 'all') {
    const isActive = statusFilter.value === 'active';
    result = result.filter(rule => rule.is_active === isActive);
  }

  return result;
});

// 获取拦截规则列表
const fetchRules = async () => {
  try {
    loading.value = true;
    const response = await interceptApi.getInterceptRules();
    
    if (response && typeof response === 'object' && Array.isArray(response.rules)) {
      rules.value = response.rules;
      
      pagination.value = {
        page: response.page || 1,
        page_size: response.page_size || 10,
        total: response.total || 0,
        pages: response.pages || 1
      };
    } else {
      // 模拟数据
      rules.value = [
        {
          id: '1',
          service_name: 'user-service',
          service_ip: '10.0.0.1',
          service_port: 8080,
          proxy_port: 9080,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          id: '2',
          service_name: 'order-service',
          service_ip: '10.0.0.2',
          service_port: 8081,
          proxy_port: 9081,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          id: '3',
          service_name: 'payment-service',
          service_ip: '10.0.0.3',
          service_port: 8082,
          proxy_port: 9082,
          is_active: false,
          created_at: new Date().toISOString()
        },
        {
          id: '4',
          service_name: 'notification-service',
          service_ip: '10.0.0.4',
          service_port: 8083,
          proxy_port: 9083,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          id: '5',
          service_name: 'auth-service',
          service_ip: '10.0.0.5',
          service_port: 8084,
          proxy_port: 9084,
          is_active: false,
          created_at: new Date().toISOString()
        }
      ];
      
      pagination.value = {
        page: 1,
        page_size: 10,
        total: rules.value.length,
        pages: 1
      };
    }
  } catch (error) {
    console.error('获取拦截规则列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取拦截状态
const fetchInterceptStatus = async () => {
  try {
    loadingStatus.value = true;
    
    // 这里应该有一个获取拦截状态的API，暂时使用模拟数据
    interceptStatus.value = {
      is_running: true,
      rules: [
        {
          id: '1',
          service_name: 'user-service',
          service_port: 8080,
          proxy_port: 9080,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          id: '2',
          service_name: 'order-service',
          service_port: 8081,
          proxy_port: 9081,
          is_active: true,
          created_at: new Date().toISOString()
        }
      ],
      start_time: new Date(Date.now() - 3600000).toISOString(),
      last_intercept_time: new Date(Date.now() - 86400000).toISOString()
    };
  } catch (error) {
    console.error('获取拦截状态失败:', error);
  } finally {
    loadingStatus.value = false;
  }
};

// 获取服务列表
const fetchServices = async () => {
  try {
    loadingServices.value = true;
    const response = await servicesApi.getAll();
    
    if (response && typeof response === 'object' && Array.isArray(response.services)) {
      services.value = response.services;
    } else {
      // 模拟数据
      services.value = [
        {
          _id: '1',
          service_name: 'user-service',
          service_ip: '10.0.0.1',
          service_port: 8080,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          _id: '2',
          service_name: 'order-service',
          service_ip: '10.0.0.2',
          service_port: 8081,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          _id: '3',
          service_name: 'payment-service',
          service_ip: '10.0.0.3',
          service_port: 8082,
          is_active: true,
          created_at: new Date().toISOString()
        }
      ];
    }
  } catch (error) {
    console.error('获取服务列表失败:', error);
  } finally {
    loadingServices.value = false;
  }
};

// 切换页码
const changePage = (page: number) => {
  if (page < 1 || page > pagination.value.pages) return;
  pagination.value.page = page;
  fetchRules();
};

// 切换规则状态
const toggleRuleStatus = async (rule: any) => {
  try {
    // 这里应该有一个切换规则状态的API，暂时使用模拟数据
    rule.is_active = !rule.is_active;
    
    // 刷新状态
    await fetchInterceptStatus();
  } catch (error: any) {
    console.error('切换规则状态失败:', error);
    alert(`切换规则状态失败: ${error.response?.data?.error || error.message}`);
  }
};

// 删除规则
const deleteRule = async (id: string) => {
  if (!confirm('确定要删除该拦截规则吗？此操作不可恢复。')) return;

  try {
    // 这里应该有一个删除规则的API，暂时使用模拟数据
    rules.value = rules.value.filter(rule => rule.id !== id);
    
    // 刷新状态
    await fetchInterceptStatus();
  } catch (error: any) {
    console.error('删除拦截规则失败:', error);
    alert(`删除拦截规则失败: ${error.response?.data?.error || error.message}`);
  }
};

// 清除所有规则
const clearRules = async () => {
  if (!confirm('确定要清除所有拦截规则吗？此操作不可恢复。')) return;

  try {
    loading.value = true;
    await interceptApi.clearInterceptRules();
    
    // 刷新状态
    await Promise.all([
      fetchInterceptStatus(),
      fetchRules()
    ]);
  } catch (error: any) {
    console.error('清除拦截规则失败:', error);
    alert(`清除拦截规则失败: ${error.response?.data?.error || error.message}`);
  } finally {
    loading.value = false;
  }
};

// 开始拦截
const startIntercept = async () => {
  if (interceptForm.value.service_ids.length === 0) {
    alert('请选择至少一个服务');
    return;
  }

  try {
    startingIntercept.value = true;
    await interceptApi.startIntercept({
      service_ids: interceptForm.value.service_ids
    });
    
    showStartInterceptModal.value = false;
    interceptForm.value.service_ids = [];
    
    // 刷新状态
    await Promise.all([
      fetchInterceptStatus(),
      fetchRules()
    ]);
  } catch (error: any) {
    console.error('开始拦截失败:', error);
    alert(`开始拦截失败: ${error.response?.data?.error || error.message}`);
  } finally {
    startingIntercept.value = false;
  }
};

// 停止拦截
const stopIntercept = async () => {
  if (!confirm('确定要停止拦截吗？')) return;

  try {
    loadingStatus.value = true;
    await interceptApi.stopIntercept({});
    
    // 刷新状态
    await Promise.all([
      fetchInterceptStatus(),
      fetchRules()
    ]);
  } catch (error: any) {
    console.error('停止拦截失败:', error);
    alert(`停止拦截失败: ${error.response?.data?.error || error.message}`);
  } finally {
    loadingStatus.value = false;
  }
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '未知';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

// 监听过滤器变化
watch([searchQuery, statusFilter], () => {
  // 如果过滤器变化，重置到第一页
  if (pagination.value.page !== 1) {
    pagination.value.page = 1;
    fetchRules();
  }
});

// 生命周期钩子
onMounted(async () => {
  await Promise.all([
    fetchRules(),
    fetchInterceptStatus(),
    fetchServices()
  ]);
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
